﻿using UnityEngine;
using UnityEngine.Extension;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System;
using System.Extension;
public enum SubjectState { Deactive, Initial, RealTime }

[Serializable]
public class ControlSubject
{
    public UnityEngine.Object content;
    public string memberPath = string.Empty;
    public SubjectState state = SubjectState.Initial;
    public bool localize, genericType;
    public object o_content = null;

    public List<string> types;
    
    object preValue;
    [NonSerialized] UnityEngine.Object m_resource;
    public bool hasContent { get { return content.isNotNone() || o_content.isNotNull(); } }
    public object value
    {
        get
        {
            object result = null;
            if (content.isNotNone()) result = content.GetValue(memberPath);
            else if (o_content.isNotNull()) result = o_content.GetValue(memberPath);
            return result;
        }
    }
    public bool hasUpdate
    {
        get
        {
            bool result = false;
            object m_value = value;
            if (state == SubjectState.RealTime && preValue.isNotNull() && m_value.isNotNull())
                result = !preValue.Equals(m_value);
            preValue = m_value;
            return result;
        }
    }
    public UnityEngine.Object resource { get { return m_resource; } }
    public ControlSubject(bool genericType, params Type[] types)
    {
        this.types = types.Select(t => t.ToString()).ToList();
        this.genericType = genericType;
    }

    public void SetObject(object item)
    {
        o_content = item;
    }

    public bool hasValidResource <T> () where T :  UnityEngine.Object
    {
        return (m_resource = GetResource<T>()) is T;
    }

    public TR GetResource<TR>() where TR : UnityEngine.Object
    {
        TR result = default(TR);
        preValue = value;
        if (preValue.isNotNull())
        {
            string path = preValue.ToString();
            if (path.isNotEmpty()) result = Resources.Load<TR>(path);
        }
        return result;
    }
}
